package com.example.myapplication.network

import android.util.Log
import com.example.myapplication.utils.AES256GCMUtil
import com.google.gson.Gson
import com.google.gson.JsonObject
import okhttp3.Interceptor
import okhttp3.Response
import okhttp3.ResponseBody
import kotlin.jvm.java

private val KEYS = arrayOf("message", "status")

class ResponseInterceptor : Interceptor {
    override fun intercept(chain: Interceptor.Chain): Response {
        val originalResponse = chain.proceed(chain.request())
        val originalBody = originalResponse.body
        val originalString = originalBody!!.string()
        val modifiedString: String = modifyResponseData(originalString)
        val modifiedBody = ResponseBody.create(originalBody.contentType(), modifiedString)
        return originalResponse.newBuilder().body(modifiedBody).build()
    }

    private fun modifyResponseData(data: String): String {
        val gson = Gson()
        try {
            val rs = AES256GCMUtil.decrypt(data, "5676dbe4ee344533a8ea882e36bfe2b4")
            val dataObject = gson.fromJson(rs, JsonObject::class.java)
            return gson.toJson(dataObject)
        } catch (e: Exception) {
            Log.d("ResponseInterceptor",e.toString())
            return data
        }
    }
}